package com.idelan.commonMessage.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;

/**
* @Description:    java类作用描述
* @Author:         jzhou
* @CreateDate:     2018\7\16 0016 14:07
* @UpdateUser:     jzhou
* @UpdateDate:     2018\7\16 0016 14:07
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
public class RabbitmqReceiverUtil {
        public static String receive(String queueName,String host,Integer port) throws Exception {
        // 获取连接
        Connection connection = RabbitmqConnectionUtil.getConnection(host,port);
        // 创建通道
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(queueName, true, false, false, null);
        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列 :true 自动确认消息
        channel.basicConsume(queueName, true, consumer);
        // 获取消息
        while (true) {
            //阻塞或轮询
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            return message;
        }
    }

    public static void main(String[] args) throws Exception {
        String host="127.0.0.1";
        Integer port=5672;
        String message= RabbitmqReceiverUtil.receive("test111",host,port);
        System.out.println("receiver message success:"+message);
    }
}
